package main

import (
	"embed"
	"io"
	"net/http"

	ginstarter "github.com/bitwormhole/starter-gin"
	"github.com/bitwormhole/starter-gin/glass"
	"github.com/bitwormhole/starter-gin/util"
	"github.com/bitwormhole/starter/collection"
	"github.com/bitwormhole/starter/io/fs"
	"github.com/bitwormhole/starter/vlog"
	"github.com/gin-gonic/gin"
)

func main() {

	//  引入依赖的模块
	devtools := ginstarter.ModuleWithDevtools()

	// 定义我的模块
	myMod := ginstarter.SimpleModule()
	myMod.Name("demo5").Version("v1").Revision(1)
	myMod.Resources(getResources())
	myMod.Dependency(devtools)
	myMod.RegisterControllerFunc(func(ec glass.EngineConnection) error {
		ec = ec.RequestMapping("/api/v1/videos/")
		ec.Handle(http.MethodGet, "", doGetVideoList)
		ec.Handle(http.MethodGet, ":id", doGetVideoData)
		return nil
	})

	// 启动服务
	i := ginstarter.InitGin()
	i.Use(myMod.Create())
	i.Run()
}

//go:embed src/main/resources
var res embed.FS

func getResources() collection.Resources {
	return collection.LoadEmbedResources(&res, "src/main/resources")
}

func getVideoDirectory(c *gin.Context) fs.Path {
	ac, err := glass.WebApplicationContext(c)
	if err != nil {
		panic(err)
	}
	val, err := ac.GetProperties().GetPropertyRequired("demo5.videos.dir")
	if err != nil {
		panic(err)
	}
	return fs.Default().GetPath(val)
}

func doGetVideoList(c *gin.Context) {

	videolist := make([]string, 0)
	dir := getVideoDirectory(c)

	if dir.IsDir() {
		list := dir.ListItems()
		for _, item := range list {
			if item.IsFile() {
				videolist = append(videolist, item.Name())
			}
		}
	}

	c.JSON(200, gin.H{
		"videolist": videolist,
	})
}

func doGetVideoData(c *gin.Context) {

	id := c.Param("id")
	file := getVideoDirectory(c).GetChild(id)
	if file.IsFile() {
		reader, err := file.GetIO().OpenReader(nil)
		if err != nil {
			panic(err)
		}
		defer reader.Close()
		c.Stream(func(w io.Writer) bool {
			count, err := util.PumpStream(reader, w, nil)
			if err != nil {
				vlog.Error(err)
			}
			vlog.Debug("PumpStream.count=", count)
			return false
		})
	}

	c.JSON(404, "HTTP 404 NOT FOUND")
}
